const initState = {
  // 优先去本地存储取值
  cartList: JSON.parse(localStorage.getItem('cartList')) || []
}


const cartReducer = (state = initState, action) =>  {
  const { type, payload } = action;
  const { cartList } = state;
  let newCarList = [...cartList]
  switch(type) {
    case 'initCartList': {
      return {
        ...state,
        cartList: payload
      }
    }
    case 'add': {
      const item = newCarList.find(v => v.id === payload.id);
      if(item) item.count++;
      else newCarList.push(payload);
      return {
        ...state,
        cartList: newCarList
      }
    }
    case 'sub': {
      const item = newCarList.find(v => v.id === payload.id);
      if(item) item.count--;
      return {
        ...state,
        cartList: newCarList
      }
    }
    case 'oneState': {
      const item = newCarList.find(v => v.id === payload.id);
      if(item) item.state = !item.state;
      return {
        ...state,
        cartList: newCarList
      }}
    case 'allState': {
      newCarList.forEach(v => {
        v.state = payload
      })
      return {
        ...state,
        cartList: newCarList
      }
    }
    case 'del': {
      newCarList = newCarList.filter(v => v.id !== payload.id);
      return {
        ...state,
        cartList: newCarList
      }
    }
    default: return state;
  }
}

export default cartReducer